<template>
  <div class="result">
    <div class="loading-container" v-show="loading">
      <me-loading />
    </div>
    <ul class="g-list" v-show="!loading && results.length">
      <li
        class="g-list-item"
        v-for="(item, index) in results"
        :key="index"
        @click="runAndadd(item)"
      >
        <span class="g-list-text">{{ item[0] }}</span>
      </li>
    </ul>
    <div class="no-result" v-show="!loading && !results.length">没有结果</div>
  </div>
</template>

<script>
import MeLoading from "../../components/loading";
import { getSearchResult } from "../../api/search";
export default {
  name: "SearchResult",
  components: {
    MeLoading,
  },
  props: {
    query: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      results: [],
      loading: false,
    };
  },
  watch: {
    query(query) {
      this.getResult(query);
    },
  },
  methods: {
    getResult(keyword) {
      if (!keyword) {
        return;
      }
      this.loading = true;
      getSearchResult(keyword).then((data) => {
        data.forEach((da) => {
          da[0] = da[0].replace(/<(?:[^>'"]|"[^"]*"|'[^']*')*>/g, "");
        });
        this.results = data;
        this.loading = false;
      });
    },
    runAndadd(val) {
      this.$store.dispatch("addHistorys", val[0]);
      this.$router.push("/detail?text=" + val);
    },
  },
};
</script>

<style scoped>
.result {
  font-size: 0.4rem;
  color: #5d656b;
  box-sizing: border-box;
  padding: 0.7rem 0.7rem;
}
.g-list-item {
  height: 1.3rem;
  line-height: 1.3rem;
  border-bottom: 1px solid #e5e5e5;
}
</style>
